package com.crm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.domain.dto.QueryCourse;
import com.crm.domain.entity.Course;
import com.crm.mapper.CourseMapper;
import com.crm.service.ICourseService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author Hulunico,Xanny
 * @since 2024-08-07
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Override
    public Page<Course> queryAll(QueryCourse queryCourse) {
        //1.设置分页参数
        /*
            请求list和请求分页都是同一个接口 如果不对空值进行初始化 会有空指针异常。
            解决方式:手动设置初始值 但ObjectUtil.isEmpty会把null也判断为对象 需要取值或者queryDictType==null
         */
        Page<Course> page = ObjectUtil.isEmpty(queryCourse.getPageNum())?Page.of(1, 10):Page.of(queryCourse.getPageNum(), queryCourse.getPageSize());

        Map<String, Object> params = queryCourse.getParams();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate beginCreateTime =ObjectUtil.isEmpty(params.get("beginCreateTime"))?null:(LocalDate.parse((String)params.get("beginCreateTime"), formatter));
        LocalDate endCreateTime =ObjectUtil.isEmpty(params.get("endCreateTime"))?null:(LocalDate.parse((String)params.get("endCreateTime"), formatter));


        //2.调用Mapper查询数据
        //2.1构建查询条件
        LambdaQueryWrapper<Course> wrapper = Wrappers.<Course>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(queryCourse.getCode()),Course::getCode, queryCourse.getCode())
                .like(ObjectUtil.isNotEmpty(queryCourse.getName()),Course::getName, queryCourse.getName())
                .eq(ObjectUtil.isNotEmpty(queryCourse.getApplicablePerson()),Course::getApplicablePerson, queryCourse.getApplicablePerson())
                .between(ObjectUtil.isNotEmpty(beginCreateTime)&&ObjectUtil.isNotEmpty(endCreateTime)
                        ,Course::getCreateTime, beginCreateTime, endCreateTime)
                .eq(ObjectUtil.isNotEmpty(queryCourse.getSubject()),Course::getSubject,queryCourse.getSubject());

        //2.2用m-plus查询
        Page<Course> coursePage = page(page, wrapper);

        return coursePage;
    }
}
